package myDemo;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-07-15
 * Time: 22:09
 */
class MyMaxHeap {

    private int[] heap;
    private final int limit;//堆的总容量
    private int usedSize;

    public MyMaxHeap(int limit){
        this.heap = new int[limit];
        this.limit = limit;
        this.usedSize = 0;
    }

    public boolean isEmpty(){
        return this.usedSize == 0;
    }

    public boolean isFull(){
        return this.usedSize == this.limit;
    }

    public void push(int value){
        if (this.usedSize == limit) {
            throw new RuntimeException("heap is full");
        }
        this.heap[this.usedSize] = value;
        heapInsert(this.heap,this.usedSize);
        this.usedSize++;
    }

    public static void swap(int[] arr,int i,int j){
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public void heapInsert(int[] heap,int child){

        while(heap[child]>heap[(child - 1) / 2]){
            //如果比父亲大就交换
            swap(heap,child,(child - 1) / 2);
            child = (child - 1) / 2;
        }
    }

    public int pop(){
        if(isEmpty()) {
            throw new RuntimeException("堆为空,不能删除");
        }
        int ans = this.heap[0];
        //堆顶元素与最后一个元素交换
        swap(this.heap,0,--this.usedSize);
        //向下调整0下标
        heapIfy(0,this.usedSize);
        return ans;
    }

    public void heapIfy(int parent,int heapSize){
        int child = 2*parent + 1;
        while(child < heapSize){
            //选错左右孩子较大的
            if(child+1 < heapSize && this.heap[child]<this.heap[child+1]){
                child = child+1;
            }
            if(this.heap[parent]>=this.heap[child]){
                break;
            }
            swap(this.heap,parent,child);
            parent = child;
            child = 2* parent + 1;
        }
    }

}